package net.mingsoft.report_data.util;

import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author gengfa
 * @date 22/03/09
 */
@Slf4j
public class ReportFtlRender {

    private ReportFtlRender() {}

    public static String render(FreeMarkerConfigurer configurer, String templateName,
                                          Map<String, Object> listVars) {
        byte[] bytes = new byte[]{};
        if (CollectionUtils.isEmpty(listVars)) {
            log.error("padding vars is empty");
            return new String(bytes, StandardCharsets.UTF_8);
        }

        bytes = generateBytes(configurer, templateName, listVars);
        return new String(bytes, StandardCharsets.UTF_8);
    }

    private static byte[] generateBytes(FreeMarkerConfigurer configurer, String templateName,
                                        Map<String, Object> variables) {
        Template tp;
        try {
            tp = configurer.getConfiguration().getTemplate(templateName);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return new byte[]{};
        }

        StringWriter stringWriter = new StringWriter();
        try (BufferedWriter writer = new BufferedWriter(stringWriter)) {
            try {
                tp.process(variables, writer);
                writer.flush();
            } catch (TemplateException e) {
                log.error("template not exists", e);
            } catch (IOException e) {
                log.error("io error", e);
            }
            return stringWriter.toString().getBytes();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return new byte[]{};
        }
    }
}
